package com.demo.security.cloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;

import javax.sql.DataSource;

/**
 * 配置Security
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 定义密码编码器
     * 定义密码的比对方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){

        // 字符串比较方式比较
//        return new BCryptPasswordEncoder();
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    // JDBC自动注入
    @Bean
    public ClientDetailsService jdbcClientDetailsService(DataSource dataSource){
        // 表的结构已经设计好了
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        // 定义Secret的比较方式
        ((JdbcClientDetailsService)clientDetailsService).setPasswordEncoder(passwordEncoder());
        return clientDetailsService;
    }

    /**
     * 配置安全拦截,拦截用户请求
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // Spring-security设置了CSRF请求拦截，可以在配置中关闭
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/r/*").authenticated()
                .anyRequest().permitAll()
                // 允许表单登录
                .and().formLogin()
                //  设置登录页面. 已经配置到index页面了 index.html
//                .loginPage("/index")
//                // 自定义登录页面中的login请求需要设置(Controller请求)
//                .loginProcessingUrl("/login")
//                // 登录成功的地址（controller请求）
//                .successForwardUrl("/hello")
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
    }


}
